<template>
  <div class="index">
    <!-- 顶部 -->
    <div class="top"><Admin></Admin></div>
    <!-- bottom -->
    <div class="bottom">
      <div class="left"><SideNav></SideNav></div>
      <div class="right">
        <div class="content">
          <el-scrollbar style="height: 100%;">
            <!-- 当前位置 -->
            <div class="current_position">
              <p class="breadcrumb">当前位置 :</p>
              <el-breadcrumb separator="/">
                <el-breadcrumb-item class="up">生活服务</el-breadcrumb-item>
                <el-breadcrumb-item class="up"><a @click="goTo('/ServiceCategory')">服务类目</a></el-breadcrumb-item>
                <el-breadcrumb-item>二级类目</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <!-- 列表 -->
            <div class="userlist">
              <div class="status_box">
                <div class="search"><el-button @click="addUser()" style="background-color: #409EFF;">新增服务类目</el-button></div>
              </div>
              <div class="table">
                <el-table ref="multipleTable" :data="tableData" border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
                  <el-table-column type="selection" fixed="left" width="50"></el-table-column>
                  <el-table-column prop="id" label="ID" width="100"></el-table-column>
                  <el-table-column prop="cname" label="分类">
                    <template slot-scope="scope">
                      <span class="cname" @click="getCategoryTwo(scope.row)">{{scope.row.cname}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="seq" label="权重"></el-table-column>
                  <el-table-column label="图片" align="center" width="265px">
                    <template slot-scope="scope">
                       <el-popover placement="left" trigger="click" width="300">
                           <img :src="scope.row.icon" width="100%" />
                           <img
                               slot="reference"
                               :src="scope.row.icon"
                               :alt="scope.row.icon"
                               style="max-height: 40px;max-width: 40px; padding: 5px"
                           />
                       </el-popover>
                    </template>
                  </el-table-column>
                  <el-table-column prop="enable" label="账号状态" align="center">
                    <template slot-scope="scope">
                      <span v-if="scope.row.status== 1" class="userStatus1">使用中</span>
                      <span v-if="scope.row.status== 0" class="userStatus2">已禁用</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" fixed="right"  width="100">
                    <template slot-scope="scope">
                      <el-button @click="redact(scope.row)" type="text" size="small">编辑</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10,20,30,40,50]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
                </el-pagination>
              </div>
            </div>
            <el-dialog  title="新增分类"  :visible.sync="dialogVisible"  width="40%"  :before-close="handleClose">
              <el-form :model="form">
                <el-form-item label="分类名" :label-width="formLabelWidth">
                  <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="权重" :label-width="formLabelWidth">
                  <el-input v-model="form.weight"></el-input>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                  <el-radio-group v-model="form.status">
                    <el-radio :label="1" >正常</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="图标" :label-width="formLabelWidth">
                  <el-upload
                    class="avatar-uploader"
                    action
                    :limit="1"
                    :show-file-list="false"
                    :http-request="handleUpload"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false,submit(form)">确 定</el-button>
                <el-button @click="dialogVisible = false">取 消</el-button>
              </span>
            </el-dialog>
            <el-dialog  title="编辑分类"  :visible.sync="dialogVisible1"  width="40%"  :before-close="handleClose1">
              <el-form :model="form1">
                <el-form-item label="分类名" :label-width="formLabelWidth1">
                  <el-input v-model="form1.cname"></el-input>
                </el-form-item>
                <el-form-item label="权重" :label-width="formLabelWidth1">
                  <el-input v-model="form1.weight"></el-input>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth1">
                  <el-radio-group v-model="form1.status">
                    <el-radio :label="1" >正常</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="图标" :label-width="formLabelWidth">
                  <el-upload
                    class="avatar-uploader"
                    action
                    :limit="1"
                    :show-file-list="false"
                    :http-request="handleUpload1"
                    :on-success="handleAvatarSuccess1"
                    :before-upload="beforeAvatarUpload1">
                    <img v-if="form1.imageUrl" :src="form1.imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible1 = false,submit1(form1)">确 定</el-button>
                <el-button @click="dialogVisible1 = false">取 消</el-button>
              </span>
            </el-dialog>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  let moment = require("moment")
  import Admin from '@/components/Admin.vue'
  import SideNav from '@/components/SideNav.vue'

  export default {
    name: 'ServicesListTwo',
    components:{
      Admin,
      SideNav
    },
    data () {
      return {
        id:'',
        page: 1,//页码
        pageSize: 50,//每页条数
        total: 0,/* 总的条数 */
        currentPage: 0,/* 前往第几页 */
        tableData: [],// 表格
        multipleSelection: [], // 选择后的列表
        dialogVisible: false,//新增服务类目
        form: {//新增分类
          name: '',
          weight: '',
          status: '',
          imageUrl: ''
        },
        formLabelWidth: '120px',
        dialogVisible1: false,//编辑服务类目
        form1: {//编辑分类
          id:'',//id
          cname: '',//名称
          weight: '',//权重
          status: '',//状态
          parentId:'',//父id
          imageUrl: ''
        },
        formLabelWidth1: '120px'
      }
    },
    mounted() {
      // 取到路由带过来的参数
      this.id = JSON.parse(JSON.stringify(this.$route.query.data.id));
      console.log('路由带过来的参数',this.id);
      this.findList();
    },
    methods: {
      // 路由
      goTo(path) {
        this.$router.push(path);
      },
      // 时间格式过滤
      dateForma(row,column){
        var date = row[column.property];
        if(date == undefined){
          return ''
        }
        return moment(date).format("YYYY-MM-DD HH:mm:ss")
      },
      // 获取所有二级服务类目
      findList(){
        this.$axios.post(this.baseURL1+'admin/goodsClassify/getAppGoodsClassifyList',{
          "page":this.page,
          "pageSize":this.pageSize,
          "parentId":this.id,//二级服务类目id
          "requestSource":"PC"
        }).then((res)=>{
          console.log(res,"所有二级服务类目");
          if(res.data.code==1){
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      // 表格的全选
      handleSelectionChange(val) {
        console.log(val);
        this.multipleSelection = val;
      },
      // 选择的每页条数
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.findList();
      },
      // 当前页面
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.page = val;
        this.findList();
      },
      //打开新增服务类目
      addUser(){
        console.log("新增服务类目")
        this.dialogVisible = true;
      },
      //关闭新增服务
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //上传新增图标 -- 新增服务类目
      handleAvatarSuccess(res, file) {
        console.log(res)
        console.log(file)
        this.form.imageUrl = URL.createObjectURL(file.raw);
      },
      //上传限制 -- 新增服务类目
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      // 获取签名 -- 新增服务类目
      getOssToken(){
        var _self = this;
        return new Promise((resolve,reject)=>{
          this.$axios.post(this.baseURL1+'getJsOssToken',{
          }).then(function(res){
            if(res.data.code==1){
              console.log(res,"通行证");
              _self.aliyunOssToken = res.data.data;
              resolve()
            }
          }).catch(function(error){
            console.log(error);
          })
        })
      },
      //上传图片 -- 新增服务类目
      handleUpload(option){
        this.getOssToken().then(res=>{
          var _self = this;
          var getSuffix = option.file.name;
          var filename = option.file.uid + getSuffix.substring(getSuffix.lastIndexOf("."),getSuffix.length);
          console.log(filename,'filename');
          var formData = new FormData();//注意formData里append添加的键的大小写
          formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
          formData.append('policy', _self.aliyunOssToken.policy); //policy
          formData.append('Signature', _self.aliyunOssToken.signature); //签名
          formData.append("file", option.file);//文件
          formData.append('success_action_status', 200); //成功后返回的操作码
          var url = _self.aliyunOssToken.host; //url
          var fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir + filename; //fileUrl文件路径
          this.$axios.post(url, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then((res) => {
            if(res.status==200){
              this.$message({
                message: '上传成功',
                type: 'success'
              });
              this.form.imageUrl = fileUrl;//赋值
              console.log(this.form.imageUrl,"图片上传成功，图片列表");
            }else{
              this.$message.error('上传失败！请重新上传');
            }
          })
          .catch((err) => {
             console.log("err:",err);
             this.$message.error('上传失败！请重新上传');
          })
        })
      },
      //提交新增分类
      submit(form){
        console.log(this.form)
        this.$axios.post(this.baseURL1+'admin/goodsClassify/saveAppGoodsClassify',{
          "cname":this.form.name,
          "parentId":this.id,//二级服务类目
          "seq":this.form.weight,
          "status":this.form.status,
          "type":"adminAdd",
          "icon":this.form.imageUrl
        }).then((res)=>{
          console.log(res,"新增二级服务类目");
          if(res.data.code==1){
            this.$message({
              type: 'success',
              message: '新增成功!'
            });
            this.findList()
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      // 打开编辑该列
      redact(row) {
        this.dialogVisible1=true
        this.form1.id= row.id//分类id
        this.form1.cname= row.cname//分类名称
        this.form1.weight = row.seq//权重
        this.form1.status = row.status//状态
        this.form1.parentId = row.parentId//父id
        this.form1.imageUrl = row.icon//父id
      },
      //关闭编辑服务
      handleClose1(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //上传新增图标 -- 新增服务类目
      handleAvatarSuccess1(res, file) {
        console.log(res)
        console.log(file)
        this.form1.imageUrl = URL.createObjectURL(file.raw);
      },
      //上传限制 -- 新增服务类目
      beforeAvatarUpload1(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
      //上传图片 -- 新增服务类目
      handleUpload1(option){
        this.getOssToken().then(res=>{
          var _self = this;
          var getSuffix = option.file.name;
          var filename = option.file.uid + getSuffix.substring(getSuffix.lastIndexOf("."),getSuffix.length);
          console.log(filename,'filename');
          var formData = new FormData();//注意formData里append添加的键的大小写
          formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
          formData.append('policy', _self.aliyunOssToken.policy); //policy
          formData.append('Signature', _self.aliyunOssToken.signature); //签名
          formData.append("file", option.file);//文件
          formData.append('success_action_status', 200); //成功后返回的操作码
          var url = _self.aliyunOssToken.host; //url
          var fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir + filename; //fileUrl文件路径
          this.$axios.post(url, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then((res) => {
            if(res.status==200){
              this.$message({
                message: '上传成功',
                type: 'success'
              });
              this.form1.imageUrl = fileUrl;//赋值
              console.log(this.form1.imageUrl,"图片上传成功，图片列表");
            }else{
              this.$message.error('上传失败！请重新上传');
            }
          })
          .catch((err) => {
             console.log("err:",err);
             this.$message.error('上传失败！请重新上传');
          })
        })
      },
      //提交编辑分类
      submit1(form1){
        console.log(this.form1)
        this.$axios.post(this.baseURL1+'admin/goodsClassify/updateAppGoodsClassify',{
          "cname":this.form1.cname,
          "id":this.form1.id,
          "parentId":this.form1.parentId,//父级服务类目
          "seq":this.form1.weight,
          "status":this.form1.status,
          "type":"adminAdd",
          "icon":this.form1.imageUrl
        }).then((res)=>{
          console.log(res,"编辑服务类目");
          if(res.data.code==1){
            this.$message({
              type: 'success',
              message: '编辑成功!'
            });
            this.findList()
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //点击一级类目获取二级类目
      getCategoryTwo(row){
        console.log(row.id)

      }
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  @import '@/assets/css/index.scss'; //这个分号一定要写，要不会报错
  @import '@/assets/css/user.scss'; //这个分号一定要写，要不会报错
  .userStatus1{
    color: #19be6b;
  }
  .userStatus2{
    color: red;
  }
  .cname{
    color: #409EFF;
    cursor: pointer;
  }
  >>> .el-dialog__header{
    border-bottom:  1px solid #dddddd;
  }
  >>> .el-dialog__title{
    font-size: 16px;
  }
  >>> .el-dialog__footer{
    text-align: center;
  }
  >>> .el-button{
    padding: 10px 15px;
  }
  //上传图标
  >>> .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  >>>.el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
</style>
